package com.jhs.kjs.handler;

import javax.servlet.http.HttpServletRequest;

import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import com.jhs.kjs.dto.UserDTO;
import com.jhs.kjs.handler.exception.AldangMessegeException;

public enum SpamPreventHandler {
	INSTANCE;

	public void addSpamFree(HttpServletRequest request, ModelAndView mav) {
		ESpamFree spamFree = getRandomSpamFree();
		request.getSession().setAttribute("spamFree", spamFree);
		mav.addObject("spamFree", spamFree.getImg());
	}

	public void addSpamFree(HttpServletRequest request, Model model) {
		ESpamFree spamFree = getRandomSpamFree();
		request.getSession().setAttribute("spamFree", spamFree);
		model.addAttribute("spamFree", spamFree.getImg());
	}

	public void checkSpamFree(HttpServletRequest request, UserDTO user) {
		ESpamFree spamFree = (ESpamFree) request.getSession().getAttribute(
				"spamFree");
		if (spamFree == null) {
			throw new AldangMessegeException("자동등록방지 문자가 잘못되었습니다.");
		}
		if (!spamFree.name().equalsIgnoreCase(user.getSecureCode())) {
			throw new AldangMessegeException("자동등록방지 문자가 잘못되었습니다.");
		}
		request.getSession().removeAttribute("spamFree");
	}

	private ESpamFree getRandomSpamFree() {
		int r = new Double(Math.ceil(Math.random() * 30)).intValue();
		int cnt = 1;
		for (ESpamFree esp : ESpamFree.values()) {
			if (r == cnt++)
				return esp;
		}
		return null;
	}

}
